package com.youlu.campus.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import com.youlu.campus.activity.entity.UserActivityQuantityRecord;
import com.youlu.campus.activity.service.UserActivityQuantityRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static java.lang.String.format;

/**
 * 用户参与活动 贡献值记录 服务
 *
 * @Description: UserActivityQuantityRecordServiceImpl
 * @Date 2025/7/30
 * @module UserActivityQuantityRecordServiceImpl
 * @author: su
 */
@Slf4j
@Service
public class UserActivityQuantityRecordServiceImpl implements UserActivityQuantityRecordService {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final int COLLECTION_COUNT = 16;

    private final ConcurrentMap<Integer, String> collectionNameCache = new ConcurrentHashMap<>();

    /**
     * 分表操作 通过活动id 的hashCode 取模 16
     *
     * @param activityId
     * @return
     */
    private String getCollectionName(String activityId) {
        return collectionNameCache.computeIfAbsent(
                Math.floorMod(activityId.hashCode(), COLLECTION_COUNT),
                k -> format("user_activity_quantity_record_%d", k)
        );
    }

    @Override
    public UserActivityQuantityRecord insert(UserActivityQuantityRecord userActivityQuantityRecord) {
        userActivityQuantityRecord.setCreateTime(new Date());
        return mongoTemplate.insert(userActivityQuantityRecord, getCollectionName(userActivityQuantityRecord.getActivityId()));
    }

    @Override
    public List<UserActivityQuantityRecord> findByInviteToUserIdAndActivityIdAndExtraPointsStatus(String inviteToUserId, String activityId, Boolean extraPointsStatus) {
        Query query = new Query().addCriteria(Criteria.where("inviteToUserId").is(inviteToUserId)
                .and("activityId").is(activityId)
                .and("extraPointsStatus").is(extraPointsStatus)
        );
        List<UserActivityQuantityRecord> userActivityQuantityRecords = mongoTemplate.find(query, UserActivityQuantityRecord.class, getCollectionName(activityId));
        return userActivityQuantityRecords;
    }

    @Override
    public void batchUpdate(List<UserActivityQuantityRecord> recordList) {
        Date date = new Date();
        for (UserActivityQuantityRecord userActivityQuantityRecord : recordList) {
            userActivityQuantityRecord.setUpdateTime(date);
        }
        for (UserActivityQuantityRecord userActivityQuantityRecord : recordList) {
            mongoTemplate.save(userActivityQuantityRecord, getCollectionName(userActivityQuantityRecord.getActivityId()));
        }
    }

    @Override
    public void deleteByUserIdAndActivityId(String userId, String activityId) {
        log.info("deleteByUserIdAndActivityId userId:{},activityId:{}", userId, activityId);
        Query query = new Query()
                .addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("activityId").is(activityId));
        DeleteResult deleteResult = mongoTemplate.remove(query, getCollectionName(activityId));
        log.info("deleteByUserIdAndActivityId deleteResult:{}", JSONObject.toJSONString(deleteResult));
    }
}
